package com.service.http.httpclient;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * 描述：
 * httpClient
 * @author xianggj
 * @Date 2021/8/30 17:06
 **/
public class HttpClientFactory {

    private HttpClientFactory() {
    }

    public static HttpClient getInstance(){
        return Singleton.INSTANCE.getInstance();
    }


    /**
     * 单例枚举
     */
    private static enum Singleton{

        INSTANCE;

        private HttpClient singleton;

        /**
         * JVM会保证此方法绝对只调用一次
         */
        private Singleton(){
            singleton = httpClient();
        }

        public HttpClient getInstance(){
            return singleton;
        }

        /**
         * 绕过ssl 验证
         * @return
         * @see [类、类#方法、类#成员]
         */
        private HttpClient httpClient()  {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(60000)
                    .setConnectTimeout(60000)
                    .setConnectionRequestTimeout(60000)
                    .build();
            SSLContext sslContext = null;
            try {
                sslContext = SSLContextBuilder.create().setProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (KeyStoreException e) {
                e.printStackTrace();
            }
            return HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
        }

    }

}
